package net.chrisrichardson.ec2deployer.applications

import net.chrisrichardson.ec2deployer.core.Application
import net.chrisrichardson.ec2deployer.core.EC2Server
import net.chrisrichardson.ec2deployer.core.ProcessExecutor
import net.chrisrichardson.ec2deployer.cluster.ClusterSpec
import net.chrisrichardson.ec2deployer.cluster.TerracottaTier
import net.chrisrichardson.ec2deployer.cluster.DatabaseTier
import net.chrisrichardson.ec2deployer.cluster.WebServerTier
import net.chrisrichardson.ec2deployer.core.AwsUtilities


class TomcatServer extends AbstractApplicationServer {

	

	String catalinaHome = '/var/lib/tomcat5'
	String catalinaHomeOther = '/usr/share/tomcat5'
    String sysconfigForTomcat = "/etc/sysconfig/tomcat5"
    String tomcatLogFile = "/var/log/tomcat5/catalina.out"


    TomcatServer() {

    }
    
    public TomcatServer(ClusterSpec clusterSpec, EC2Server host, DatabaseTier databaseTier, TerracottaTier terracottaTier, WebServerTier webServerTier) {
		super(clusterSpec, host, databaseTier, terracottaTier, webServerTier);
    }

    public void startTomcat() {
		assert host.isRunning()
		databaseTier.grantAccessToClient(this)

        stopService "tomcat5"

        if (clusterSpec.webAppBundle)
            installWebAppBundle(clusterSpec.webAppBundle)
        else
           clusterSpec.webApps.each{it.updateTomcat(this, clusterSpec.bucketPrefix)}

		writeFile fileName: "$catalinaHomeOther/conf/server.xml", templateName: "/templates/server.xml", templateArgs: [jvmRoute: jvmRoute]

        terracottaTier.prepareClient host

        appendToFile fileName: "${sysconfigForTomcat}", text: """export CATALINA_OPTS='${makeCatalinaOpts()}'
export JAVA_HOME=/usr/java/default
"""
        startService "tomcat5"
	}

    void installWebAppBundle(String webAppBundle) {
        def tarFile = "/var/tmp/snapshot.tar"
        AwsUtilities awsUtilities = new AwsUtilities(host)
        awsUtilities.s3get webAppBundle, "/var/tmp/snapshot.tar"
        exec "cd $catalinaHome/webapps; tar xf $tarFile"
    }

    String snapshotWebApplications() {
        String object = UUID.randomUUID().toString() + ".tar"
        String bucket = "${host.awsProperties.accessKey}.tmp-clone-db"
        def tarFile = "/var/tmp/snapshot.tar"
        def s3Path = "$bucket/$object"

        exec "cd $catalinaHome/webapps; tar cf $tarFile ."

        AwsUtilities awsUtilities = new AwsUtilities(host)
        awsUtilities.s3put s3Path, tarFile

        s3Path
    }

	public void stopTomcat() {
        stopService "tomcat5"
    }


    void updateWar(String explodedWar, String s3Path) {
        String warFileName = s3Path.substring(s3Path.lastIndexOf('/') + 1)
        String warDir = "/tmp/" + warFileName.substring(0, warFileName.lastIndexOf('.'))
        String destWarFile = "/tmp/$warFileName"

        AwsUtilities awsUtilities = new AwsUtilities(host)
        awsUtilities.s3get(s3Path, destWarFile)

        host.ssh "mkdir $warDir"
        host.ssh "cd $warDir ; jar xf $destWarFile"

        ProcessExecutor pe = new ProcessExecutor()
        pe.execute "rsync --del -u -v -r -e \"ssh -i ${host.awsProperties.keyPairFile} \" ${explodedWar}/ root@${host.publicDnsName}:$warDir"

        host.ssh "rm -f $destWarFile"
        host.ssh "cd $warDir ; jar cf $destWarFile ."
        awsUtilities.s3put s3Path, destWarFile
     }

    File getTomcatLog() {
        File logFile = File.createTempFile("applog", ".log");
        logFile.withWriter {Writer writer ->
            def logFileProcessMonitor = new StdoutCapturingProcessMonitor(writer)
            host.ssh "cat $tomcatLogFile", null, logFileProcessMonitor
        }
        return logFile
    }


    String getDeploymentDirectory() {
        return "${catalinaHome}/webapps"
    }

    boolean supportsExplodedWars() {
        return true
    }

}